import React, { useState, useEffect, useCallback } from "react";
import {
  Card,
  Button,
  Slider,
  Space,
  message,
  Spin,
  Row,
  Col,
  Statistic,
  Select, 
} from "antd";
import { Map, APILoader, Polyline, Marker } from "@uiw/react-amap";
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  ReloadOutlined,
  CarOutlined,
} from "@ant-design/icons";
import config from "../../config/config";
import "./style.less";

const { Option } = Select;

const MapTrack = () => {
  const [loading, setLoading] = useState(true);
  const [mapInstance, setMapInstance] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [playbackSpeed, setPlaybackSpeed] = useState(1);

  // 模拟轨迹数据
  const trackData = [
    { position: [120.1551, 30.2539], time: "10:00", speed: 30 },
    { position: [120.1601, 30.2579], time: "10:05", speed: 35 },
    { position: [120.1651, 30.2619], time: "10:10", speed: 40 },
    { position: [120.1701, 30.2659], time: "10:15", speed: 25 },
    // ... 更多轨迹点
  ];

  // 处理地图加载完成
  const handleMapComplete = useCallback((map) => {
    setMapInstance(map);
    setLoading(false);
    message.success("地图加载完成");
  }, []);

  // 播放控制
  const togglePlay = () => {
    setIsPlaying(!isPlaying);
  };

  // 重置播放
  const resetPlayback = () => {
    setIsPlaying(false);
    setCurrentIndex(0);
  };

  // 轨迹回放逻辑
  useEffect(() => {
    let timer;
    if (isPlaying && currentIndex < trackData.length - 1) {
      timer = setTimeout(() => {
        setCurrentIndex((prev) => prev + 1);
      }, 1000 / playbackSpeed);
    } else if (currentIndex >= trackData.length - 1) {
      setIsPlaying(false);
    }
    return () => clearTimeout(timer);
  }, [isPlaying, currentIndex, playbackSpeed, trackData.length]);

  // 渲染轨迹线
  const renderPath = () => {
    const path = trackData
      .slice(0, currentIndex + 1)
      .map((point) => point.position);
    return (
      <Polyline
        path={path}
        strokeColor="#1890ff"
        strokeWeight={6}
        strokeOpacity={0.8}
      />
    );
  };

  // 渲染车辆标记
  const renderCarMarker = () => {
    const currentPoint = trackData[currentIndex];
    return (
      <Marker
        position={currentPoint.position}
        offset={[-15, -15]}
        visiable={true}
      >
        <div className="car-marker">
          <CarOutlined style={{ fontSize: 24, color: "#1890ff" }} />
        </div>
      </Marker>
    );
  };

  return (
    <div className="map-track-container">
      <Card title="轨迹回放">
        <APILoader {...config.mapConfig}>
          <div style={{ height: "500px", position: "relative" }}>
            <Map
              zoom={14}
              center={trackData[currentIndex].position}
              onComplete={handleMapComplete}
            >
              {!loading && (
                <>
                  {renderPath()}
                  {renderCarMarker()}
                </>
              )}
            </Map>
            {loading && (
              <div className="map-loading">
                <Spin tip="地图加载中..." />
              </div>
            )}
          </div>
        </APILoader>

        <div className="playback-controls">
          <Row gutter={[16, 16]}>
            <Col span={6}>
              <Statistic
                title="当前时间"
                value={trackData[currentIndex].time}
              />
            </Col>
            <Col span={6}>
              <Statistic
                title="当前速度"
                value={trackData[currentIndex].speed}
                suffix="km/h"
              />
            </Col>
          </Row>

          <div className="timeline">
            <Slider
              min={0}
              max={trackData.length - 1}
              value={currentIndex}
              onChange={setCurrentIndex}
              tooltipVisible={false}
            />
          </div>

          <Space className="controls">
            <Button
              type="primary"
              icon={
                isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />
              }
              onClick={togglePlay}
            >
              {isPlaying ? "暂停" : "播放"}
            </Button>
            <Button icon={<ReloadOutlined />} onClick={resetPlayback}>
              重置
            </Button>
            <div className="speed-control">
              <span>播放速度：</span>
              <Select
                value={playbackSpeed}
                onChange={setPlaybackSpeed}
                style={{ width: 100 }}
              >
                <Option value={0.5}>0.5x</Option>
                <Option value={1}>1.0x</Option>
                <Option value={2}>2.0x</Option>
                <Option value={4}>4.0x</Option>
              </Select>
            </div>
          </Space>
        </div>
      </Card>
    </div>
  );
};

export default MapTrack;
